package com.amorcloud.pig.activity;

import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.amorcloud.pig.R;
import com.amorcloud.pig.bean.UserInfoBean;
import com.amorcloud.pig.utils.UserDaoUtils;

public class AddUserActivity extends BaseActivity implements View.OnClickListener {

    EditText mUserName, mPwd, mConfirmPwd;
    Button mSave, mCancel;

    @Override
    protected void init() {
        setContentView(R.layout.activity_add_user);
        initCustomToolbar(this);
        initView();
        initData();
    }

    private void initView() {
        mUserName = findViewById(R.id.etv_username);
        mPwd = findViewById(R.id.etv_pwd);
        mConfirmPwd = findViewById(R.id.etv_add_user_confirm_pwd);
        mSave = findViewById(R.id.btn_add_user);
        mSave.setOnClickListener(this);
        mCancel = findViewById(R.id.add_user_btn_cancle);
        mCancel.setOnClickListener(this);
    }

    private void initData() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.add_user_btn_cancle:
                this.finish();
                break;
            case R.id.btn_add_user:
                addUser();
                break;
            default:
                break;
        }
    }

    private void addUser() {
        String username = mUserName.getText().toString();
        String pwd = mPwd.getText().toString();
        String confirPwd = mConfirmPwd.getText().toString();
        if(TextUtils.isEmpty(username) || TextUtils.isEmpty(pwd) || TextUtils.isEmpty(confirPwd)) {
            Toast.makeText(this, "账号或密码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if(pwd.length() < 6) {
            Toast.makeText(this, "密码不能少于六位", Toast.LENGTH_SHORT).show();
            return;
        }
        if(!pwd.equals(confirPwd)) {
            Toast.makeText(this, "两次输入密码不一致", Toast.LENGTH_SHORT).show();
            return;
        }

        UserInfoBean userInfoBean = new UserInfoBean();
        userInfoBean.setUserName(username);
        userInfoBean.setPasswrod(pwd);
        userInfoBean.setIsAdmin("0");
        long res = UserDaoUtils.insertUser(userInfoBean);
        Log.d("leihuiming", "res = " + res);
        //clearData();
        Toast.makeText(this, "增加成功", Toast.LENGTH_SHORT).show();
        finish();
    }

    private void clearData() {
        mUserName.setText("");
        mPwd.setText("");
        mConfirmPwd.setText("");
        mUserName.requestFocus();
    }
}
